//
//  WBNetworkManager+Extension.swift
//  Weibo
//
//  Created by cc on 9/15/17.
//  Copyright © 2017 cc. All rights reserved.
//

import Foundation




// MARK: - 封装 新浪微博的网络请求方法
extension WBNetworkManager {
    
    
    
    /// 加载微博数据字典数组
    ///
    ///   - since_id: 返回ID比since_id大的微博(即比since_id時間晚的微博， 默認為0)
    ///   - max_id:   返回ID小於或等於max_id的微博，默認為0
    /// - Parameter complete: 完成回调[微博字典数组 / 是否成功]
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, complation:@escaping (_ list: [[String: Any]]?,_ isSuccess: Bool)->()) {
        
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
//        let params = ["access_token": "2.00NKbMECwXsXJB81a1831dffN9yRFC"]
        

        //Swift 中， Int 能轉 AnyObject， 但是 Int64不行
        let params = ["since_id": since_id, "max_id": max_id > 0 ? max_id - 1 : 0]
        
        tokenRequest(URLString: urlString, parameters: params) { (json , isSuccess) in
            
            // 从  json 中获取 statuses 字典数组
            // 如果 as？ 失败， result = nil
            //提示： 服務器返回的字典數組，就是按照時間的倒序排序的
            
            guard let json = json else {
                return
            }
            let result = (json as! NSDictionary)["statuses"] as? [[String: Any]]
            
            complation(result, true)
            
        }

    }

    
    /// 返回微博的未读数量
    func unreadCount(completion:@escaping (_ count: Int)->()) {
        
        guard let uid = uid else {
            return
        }
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid": uid]
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            let dict = json as? [String:Any]
            
            let count = dict?["status"] as? Int
            
            completion(count ?? 0)
        }
    }
}



// MARK: - OAuth相关方法
extension WBNetworkManager {
    
    
    /// 加载accessToken
    func loadAccessToken (code: String) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": WBAppKey, "client_secret": WBAppSecret, "grant_type": "authorization_code", "code": code, "redirect_url": WBRedirectUrl ]
        
        request(method: .POST, URLString: urlString, parameters: params, completion: { (json, isSuccess) in
            print(json ?? "")
        })
        
        
    }
}







